package p03_SingleLinkedList.quiz.q03_剑指Offer06_从尾到头打印链表;


import java.util.Stack;

//Definition for singly-linked list.
public class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

class Solution {
    public int[] reversePrint(ListNode head) {
        int len = getLength(head);
        int[] arr = new int[len];
        ListNode temp = head;
        int c = len - 1;
        while (temp != null) {
            arr[c] = temp.val;
            temp = temp.next;
            c--;
        }
        return arr;
    }

    public static int getLength(ListNode head) {
        if (head == null) {
            return 0;
        }
        int len = 0;
        ListNode temp = head;
        while (temp != null) {
            temp = temp.next;
            len++;
        }
        return len;
    }

    /**
     * 栈
     * @param head
     * @return
     */
    public int[] reversePrint1(ListNode head) {
        Stack<ListNode> stack = new Stack<ListNode>();
        ListNode temp = head;
        while (temp != null) {
            stack.push(temp);
            temp = temp.next;
        }
        int size = stack.size();
        int[] arr = new int[size];
        for (int i = 0; i < size; i++) {
            arr[i] = stack.pop().val;
        }
        return arr;
    }
}
